//
//  HMSinaStatusesCellViewModel.swift
//  ZJCSina
//
//  Created by 朱建超 on 16/11/18.
//  Copyright © 2016年 itHeiMa. All rights reserved.
//
//微博cell的视图模型，用来处理微博cell显示数据

import UIKit
import YYText

class HMSinaStatusesCellViewModel: NSObject {

    //增加一个url属性，用来记录用户头像地址
    var iconURL : URL?
    
    var userTypeImage : UIImage?
    
    var levelImage : UIImage?
    
    var sourceText : String?
    
    //设置行高,只希望计算一次，以后就直接读取
    var rowheight : CGFloat = 300
    
    //原创微博的属性字符串
    var originalString : NSMutableAttributedString?
    
    //转发微博的属性字符串
    var zhuanFaString : NSMutableAttributedString?
    
    var timeText : String?{
    
        //使用分类中的方法
        return Date.createDateStrint(createAtStr: statusesCell?.created_at ?? "")
    
    }
    
    //计算型属性，判断应该返回什么类型微博的pic_urls
    var imageURL : [HMSinaPictures]?{
    
        if statusesCell?.retweeted_status == nil {
            
            //原创微博
            return statusesCell?.pic_urls
            
        }
    
        //转发微博
        return statusesCell?.retweeted_status?.pic_urls
        
    }
    
    var statusesCell : HMSinaStatuses?{
    
        didSet{
        
            //一旦外界设置值，就应该在didSet中计算用户头像的地址
            iconURL = URL(string: statusesCell?.user?.avatar_large ?? "")
           
            detailUersTypeImage()
            
            detailUserLevel()
            
            self.sourceText = detailSource(source: statusesCell?.source ?? "")
            self.originalString =  detailWeiBoSring(string: statusesCell?.text ?? "")
            self.zhuanFaString = detailWeiBoSring(string: statusesCell?.retweeted_status?.text ?? "")
        }
    
    }
    
    //将微博正文和转发的微博处理成富文本
    private func detailWeiBoSring(string : String) -> NSMutableAttributedString {
        
        //实例化正则表达式对象,设置查找规则
//        let pattern = "\\[.*?\\]"
        
//        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        
        //通过规则，在字符串中查找目标字符串 --> [NSTextCheckResult]
        let results : [NSTextCheckingResult] = emotionRegex.matches(in: string, options: [], range: NSRange(location: 0, length: string.characters.count))
        
        //遍历结果集，获取表情字符串 -->倒序遍历
        //将string转换为可变的富文本
        let Mstring = NSMutableAttributedString(string: string)
        let font = UIFont.systemFont(ofSize: 15)
        let lineHeight = font.lineHeight
        
        for result in results.reversed() {
            
            let range = result.rangeAt(0)
            
            let sub = (string as NSString).substring(with: range)
            
            //根据表情字符串，在表情数组中，查找对应的表情模型
            if let emotion = HMEmoticonTools.sharedEmoticonTools.findEmoticon(chs: sub){
            
                //查找到表情后进行后续的操作
                
                //将图片转换为富文本，必须使用YYText提供的富文本的实例化方法
                let image = UIImage(named: emotion.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
                
                let imageText = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit, attachmentSize: CGSize(width: lineHeight , height: lineHeight), alignTo: font, alignment: .center)
                
                //将图片富文本替换到string对应的富文本中
                Mstring.replaceCharacters(in: range, with: imageText)
            
            }
        
        }
        //给富文本添加字体的实型
        Mstring.addAttributes([NSFontAttributeName : font], range: NSRange(location: 0, length: Mstring.length))
        
        addHighlighted(regex: contactSomeOneRegex, string: Mstring)
        addHighlighted(regex: huaTiRegex, string: Mstring)
        addHighlighted(regex: httpRegex, string: Mstring)
        
//        addHighlighted(pattern: "@\\w+", string: Mstring)
//        addHighlighted(pattern: "#.*?#", string: Mstring)
//        addHighlighted(pattern: "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?", string: Mstring)
        
        return Mstring
        
    }
    
    //给特殊文本添加高亮
    private func addHighlighted(regex : NSRegularExpression , string : NSMutableAttributedString) {
        
        //先给@某人添加高亮
//        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        
        let str = string.string
        
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        
        for result in results {
            
            let range = result.rangeAt(0)
            
//            let sub = (str as NSString).substring(with: range)
            
            let color = UIColor(red: 235.0/255.0, green: 126.0/255.0, blue: 40.0/255.0, alpha: 0.2)
            
            //给目标字符串添加颜色
            string.addAttributes([NSForegroundColorAttributeName : UIColor.orange], range: range)
            
            //给url添加跳转的点击事件  使用YYText
            let border = YYTextBorder(fill: color, cornerRadius: 3)

            let highlighted = YYTextHighlight()
            highlighted.setBackgroundBorder(border)
            
            //把高亮设置到某个文本的范围
            string.yy_setTextHighlight(highlighted, range: range)
            
        }
        
        
    }
    
    //处理微博来源
    //<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">微博 weibo.com</a>
    private func detailSource(source : String) -> String {
        
        let startFlag = "\">"
        let endFlag = "</a>"
        
        guard let startRange = source.range(of: startFlag),
            let endRange = source.range(of: endFlag)else{
        return "来自火星"
        
        }
        //upperBound 最大边界
        let range = startRange.upperBound..<endRange.lowerBound
        let string = source.substring(with: range)
        return string
        
    }
    
    //处理用户等级的方法
    private func detailUserLevel() {
        
        let level = statusesCell?.user?.mbrank ?? 0
        if level > 0 && level < 7 {
         
            levelImage = UIImage(named: "common_icon_membership_level\(level)")
        
        }
        
    }
    
    //处理用户类型的方法
    private func detailUersTypeImage() {
        
        //处理微博认证的图片
        let userType = statusesCell?.user?.verified_type ?? -1
        
        //判断type
        //认证信息 : -1没有认证 0认证用户 2、3、5企业认证  220达
        switch userType {
        case 0:
            userTypeImage = #imageLiteral(resourceName: "avatar_vip")
        case 2,3,5:
            userTypeImage = #imageLiteral(resourceName: "avatar_enterprise_vip")
        case 220:
            userTypeImage = #imageLiteral(resourceName: "avatar_grassroot")
        default:
            //没有认证
            userTypeImage = nil
        }
        
    }
    
    //处理数据相关的业务逻辑  处理微博日期、来源
    
}
